// movie database connection

/*
 * Queries the movie database.
 * 
 * Returns a Movies object from tMDb.
 */
 
function TmdbConnection() {
}

TmdbConnection.query = function(t) {
	jQuery.getJSON(
		'http://api.themoviedb.org/3/search/movie',
		{
			api_key: '8974c48b90e1fd0f122e66481cb737ad',
			query: t
		},
		/* callback - prints results to a table */
		function(response) {
			var movieList = new Array();
			var x = 0;
			
			/* 
			 * Convert results into MovieInfo objects.
			 *
			 * TODO scrap MovieInfo object, it adds an unnecessary step
			 */
			for( i in response.results ) { // r == index of movie in pages[p]
				var m = response.results[i];

				/* we only offer movies with poster urls */
				if (m.poster_path != null ) {
					movieList[x++] = new MovieInfo( m );
				}
			}
						
			HtmlFactory.printResults(movieList);
		} // response callback
	); // getJSON
}

TmdbConnection.getDetails = function(movieId) {
	jQuery.getJSON(
		'http://api.themoviedb.org/3/movie/' + movieId,
		{
			api_key: '8974c48b90e1fd0f122e66481cb737ad',
		},
		/* callback - prints results to page */
		function(details) {
			HtmlFactory.printDetails(details);
		});
}

TmdbConnection.getHist = function() {
	var u = User.read();
	
	if (u.rentals.length == 0) {
		$("#results").html("<h2>You have no history items</h2>");
	}
	
	$.each(u.rentals, function(i, movieId) {
		jQuery.getJSON(
			'http://api.themoviedb.org/3/movie/' + movieId,
			{
				api_key: '8974c48b90e1fd0f122e66481cb737ad',
			},
			/* callback - prints results to page */
			function(movieData) {
				console.log(movieData);
				// this method takes a list, so we create a 1 element list
				HtmlFactory.printResults([new MovieInfo( movieData )]);
			});
		});
}

TmdbConnection.getRecommendations = function(user) {
	jQuery.getJSON(
		'http://api.themoviedb.org/3/movie/' + user.rentals[user.rentals.length-1] + '/similar_movies',
		{
			api_key: '8974c48b90e1fd0f122e66481cb737ad'
		},
		/* callback - prints results to page */
		function(response) {
			var movieList = new Array();
			var x = 0;
			
			/* 
			 * Convert results into MovieInfo objects.
			 *
			 * TODO scrap MovieInfo object, it adds an unnecessary step
			 */
			for( i in response.results ) { // r == index of movie in pages[p]
				var m = response.results[i];

				/* we only offer movies with poster urls */
				if (m.poster_path != null ) {
					movieList[x++] = new MovieInfo( m );
				}
			}
			HtmlFactory.printResults(movieList);
	});
}